package com.hj.hos.service;

import cn.hutool.core.text.CharPool;
import com.hj.hos.HosService;
import com.hj.hos.properties.HosProperties;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author hj
 * @Date 2023/4/29
 * @Description: 七牛云存储
 */
public class QiniuHosService extends HosService {
    private final UploadManager uploadManager;
    private final String token;

    public QiniuHosService(HosProperties properties) {
        this.properties = properties;

        uploadManager = new UploadManager(new Configuration(Region.autoRegion()));
        token = Auth.create(properties.getQiniu().getAccessKey(), properties.getQiniu().getSecretKey()).
                uploadToken(properties.getQiniu().getBucketName());
    }

    @Override
    public String upload(byte[] data, String path) {
        try {
            Response res = uploadManager.put(data, path, token);
            if (!res.isOK()) {
                throw new RuntimeException("七牛云存储--上传文件失败：");
            }
            return properties.getConfig().getDomain() + CharPool.SLASH + path;
        } catch (Exception e) {
            throw new RuntimeException("七牛云存储--上传文件失败：", e);
        }
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new RuntimeException("七牛云存储--上传文件失败：", e);
        }
    }

}
